<template>
  <a-modal
    :dialogClass="madalClass"
    :visible="winConfig.visible"
    :width="winConfig.width"
    :confirm-loading="winConfig.loading"
    @ok="
      () => {
        modalEvent('ok')
      }
    "
    @cancel="
      () => {
        modalEvent('cancel')
      }
    "
    :footer="null"
  >
    <div slot="title" class="title-con">
      <div class="title" :title="winConfig.title">{{ winConfig.title }}</div>
      <div class="btn-group">
        <a-button type="dashed" icon="download" @click="uploads" style="margin: 0 5px">下 载</a-button>
        <a-button type="dashed" @click="enlarge" style="margin: 0 5px">{{ enlargeLabel }}</a-button>
      </div>
    </div>
    <div class="data-con" :style="{ height: `calc(${winConfig.height} - 140px)` }">
      <component  v-if="!showCarousel" :is="componentNameList[mark+'0']" :url="url" :setEvent="setWatermarkFile"></component>
      <a-carousel
        v-if="showCarousel"
        arrows
        :after-change="onChange"
        style="width: 100%; height: 100%"
        class="carousel-con"
        :dots-class="'dots-item'"
      >
        <div slot="prevArrow" slot-scope="props" class="custom-slick-arrow" style="left: 10px">
          <!-- <a-icon type="left-circle" /> -->
          <a-button type="primary" shape="circle" icon="left-circle"></a-button>
        </div>
        <div slot="nextArrow" slot-scope="props" class="custom-slick-arrow" style="right: 10px">
          <!-- <a-icon type="right-circle" /> -->
          <a-button type="primary" shape="circle" icon="right-circle"></a-button>
        </div>
        <div class="item-con" v-for="(item,index) in url">
          <!-- {{mark+index}}
          {{item}}
          {{componentNameList[mark+index]}} -->
          <component :is="componentNameList[mark+index]" :url="item" :setEvent="setWatermarkFile" :order="index"></component>
        </div>

      </a-carousel>
    </div>
  </a-modal>
</template>

<script>
import { adddWatermark, base64Img2Blob } from './utils/Watermark'
import { getCaptionFileName } from '@/utils/util'
// import { parseOfdDocument, renderOfd } from 'ofd.js'
import * as OFDUils from 'ofd.js'
// console.log('OFDUils===>', OFDUils);
const imgBox = {
  props: {
    url: { type: String },
    setEvent: { type: Function },
  },
  data() {
    return {
      dataUrl: '',
    }
  },
  watch: {
    url: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object String]') {
          adddWatermark(val).then((res) => {
            this.dataUrl = res
          })
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // async adddWatermark(url) {
    //   console.log('adddWatermark 0===>',url);
    //   const res =  await Watermark({
    //       url: url,
    //       content: ['请勿外传', '2023年2月9日'],
    //     })
    //     // console.log('adddWatermark===>',res.base64);
    //     this.dataUrl = res.base64
    //     return res.base64
    // },
  },
  render: function (h) {
    const { url, dataUrl } = this
    // console.log('imgBox ====>', dataUrl);
    this.setEvent && this.setEvent(dataUrl)
    return h('img', {
      domProps: {
        src: dataUrl || url,
      },
      class: { 'img-box': true },
    })
  },
}
const iframeBox = {
  props: {
    url: { type: String },
    setEvent: { type: Function },
  },
  render: function (h) {
    const { url } = this
    return h('iframe', {
      domProps: {
        sandbox: 'allow-scripts allow-top-navigation allow-same-origin allow-popups allow-forms',
        frameborder: '0',
        src: `https://view.officeapps.live.com/op/view.aspx?src=${url}`,
      },
      style: { height: '100%', width: '100%' },
      class: { 'img-box': true },
    })
  },
}

const pdfBox = {
  props: {
    url: { type: String },
    order: { type: [String,Number] },
    setEvent: { type: Function },
  },
  watch: {
    url: {
      handler(val) {
        // console.log('pdfBox 000=>',val,PDFObject, document.getElementById('pdfBox'));
        if(val){
          const { url,order } = this
          this.$nextTick(()=>{
            // console.log('pdfBox 111=>',val,PDFObject, document.getElementById('pdfBox'));
            document.getElementsByClassName('pdfBox-con-'+order).forEach(item=>{
              PDFObject.embed(val, item)
            })
          })
        }
      },
      deep: true,
      immediate: true,
    },
  },
  render: function (h) {
    const { url,order } = this
    const tempClass = {'img-box': true, ['pdfBox-con-'+order]:true}
    return h('div', {
      domProps: {
        id: 'pdfBox',
      },
      style: { height: '100%', width: '100%' },
      class: { ...tempClass },
    })
  },
}
const textBox = {
  props: {
    value: { type: String },
    setEvent: { type: Function },
  },
  render: function (h) {
    const { value } = this
    return h(
      'div',
      {
        domProps: {
          id: 'txtBox',
        },
        style: { height: '100%', width: '100%' },
        class: { 'img-box': true },
      },
      value
    )
  },
}

const downLondBox = {
  props: {
    url: { type: String },
    setEvent: { type: Function },
  },
  render: function (h) {
    const { url } = this
    return h(
      'div',
      {
        domProps: {
          // sandbox: 'allow-scripts allow-top-navigation allow-same-origin allow-popups allow-forms',
          // frameborder: '0',
          // src: '#',
          // style:'display: flex; justify-content: center; align-items: center;'
        },
        class: { 'img-box': true },
      },
      [<a-result status="warning" sub-title="当前文件不支持在线预览，可下载后查看！"></a-result>]
    )
  },
}

const odfBox = {
  props: {
    url: { type: String },
    setEvent: { type: Function },
  },
  methods: {
    getOfdDocumentObj(file, screenWidth) {
      let that = this
      // let t = new Date().getTime();
      // this.loading = true;
      OFDUils.parseOfdDocument({
        // ofd: file,
        ofd: file,
        // secret: 'kgNVVbdUZ31C6mps',
        // secret: '',
        // signaturesCallback(signatures) {
        //   // console.log(signatures)
        //   let screenWidth = 1050 //设置内容的显示框大小
        //   //将流数据渲染给接受的div盒子
        //   OFDUils.renderOfd(0, screenWidth).then((res) => {
        //     const divs = res
        //     that.displayOfdDiv(divs);
        //     // let contentDiv = document.getElementById('divId') // 获取盒子元素
        //     // contentDiv.innerHTML = ''
        //     // for (const div of divs) {
        //     //   contentDiv.appendChild(div)
        //     // }
        //   })
        // },
        success(res) {
          console.log(res)
          // let t1 = new Date().getTime();
          console.log('解析ofd', res, file)
          // that.ofdObj = res[0];
          // that.pageCount = res[0].pages.length;
          // const divs = OFDUils.renderOfd(screenWidth, res[0]);
          // // let t2 = new Date().getTime();
          // // console.log('xml转svg', t2 - t1)
          // that.displayOfdDiv(divs);
          // let t3 = new Date().getTime();
          // console.log('svg渲染到页面', t3 - t2);
          // that.loading = false;
        },
        fail(error) {
          console.log('错误===》', error)
          // that.loading = false;
          // that.$alert('OFD打开失败', error, {
          //   confirmButtonText: '确定',
          //   callback: action => {
          //     this.$message({
          //       type: 'info',
          //       message: `action: ${action}`
          //     });
          //   }
          // });
        },
      })
    },
    geturl2File4OFD(url, fileName) {
      return new Promise((resolve, reject) => {
        var blob = null
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.setRequestHeader('Accept', 'application/ofd')
        xhr.responseType = 'blob'
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
          blob = xhr.response
          let file = new File([blob], fileName, { type: 'application/ofd' })
          console.log('geturl2File4OFD===>', file)
          // 返回结果
          resolve(file)
        }
        xhr.onerror = (e) => {
          reject(e)
        }
        // 发送
        xhr.send()
      })
    },
    displayOfdDiv(divs) {
      // this.scale = getPageScale();
      let contentDiv = document.getElementById('ofdBox')
      contentDiv.innerHTML = ''
      for (const div of divs) {
        contentDiv.appendChild(div)
      }
      // for(let ele of document.getElementsByName('seal_img_div')) {
      //   this.addEventOnSealDiv(ele, JSON.parse(ele.dataset.sesSignature), JSON.parse(ele.dataset.signedInfo));
      // }
    },
    pageInit() {
      const screenWidth = document.getElementById('ofdBox').clientWidth
      const fileName = getCaptionFileName(this.url)
      this.getOfdDocumentObj(this.url, screenWidth)
      // this.geturl2File4OFD(this.url, fileName).then(res => {
      //   console.log('getOfdDocumentObj 0===>', res, screenWidth);
      //   this.getOfdDocumentObj(res, screenWidth)
      // })
    },
  },
  mounted() {
    this.pageInit()
  },
  render: function (h) {
    const { url } = this

    return h('div', {
      domProps: {
        id: 'ofdBox',
      },
      class: { 'img-box': true },
    })
  },
}

const getFileSuffix = (filePath) => {
  const res = { suffix: '', name: '' }
  var startIndex = filePath.lastIndexOf('.')
  const name = filePath.match(/[^//]+$/)[0]
  res.name = name
  if (startIndex != -1) res.suffix = filePath.match(/[^.]+$/)[0] // filePath.substring(startIndex + 1, filePath.length).toLowerCase();
  // else return "";
  return res
}

export default {
  name: 'previewShow',
  components: { imgBox, iframeBox, pdfBox, downLondBox, textBox, odfBox },
  props: {
    config: { type: Object }, // 用于设置弹窗的  {title:'',visible: false, loading: false, width: '50vw',height: '60vh' }
    url: { type: [String, Array] }, // 用于显示的文件的地址
    name: { type: [String, Array] }, // 文件名称
    suffix: { type: [String, Array] }, // 文件后缀
    event: { type: Function }, // 执行的事件 关闭
  },
  data() {
    return {
      mark:'item',
      componentConfig: {
        componentName: '',
      },
      componentNameList:{},
      // 是否启用多文件预览 false 表示单位件预览  true 表示多文件预览
      showCarousel: false,
      previewUrlList: [],
      madalClass: '',
      isEnlarge: false,
      enlargeLabel: '全 屏',
      winConfig: {
        title: '',
        visible: false,
        loading: false,
        width: '50vw',
        height: '60vh',
      },
      dataUrl: {},
      // 用于下载带有水印的文件
      downLoadWatermarkFile: null,
      fileName: {},
    }
  },

  watch: {
    config: {
      handler(val) {
        if (Object.prototype.toString.call(val) === '[object Object]') {
          this.winConfig = Object.assign(
            {},
            JSON.parse(JSON.stringify(this.winConfig)),
            JSON.parse(JSON.stringify(val))
          )
        }
      },
      deep: true,
      immediate: true,
    },
    url: {
      handler(val) {
        // console.log('2222222222222',val,this.suffix,this.name);
        if (Object.prototype.toString.call(val) === '[object String]' && val.length > 0) {
          // this.getComponentInfo('zip', val)
          this.showCarousel = false
          this.previewUrlList = [val]
          this.dataHandling(val, this.mark + '0',0)
          // this.dataUrl = val
        }
        if (Object.prototype.toString.call(val) === '[object Array]' && val.length > 0) {
          this.previewUrlList = [...val]
          this.showCarousel = true
          val.forEach((item, index) => {
            this.dataHandling(item, this.mark + index,index)
            // this.$nextTick(()=>{
            // })
          })
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    onChange(a, b, c) {
      // console.log(a, b, c)
      let currentTitle = ''
      const key = this.mark + a
      if(Object.prototype.toString.call(this.name) === '[object Array]'){
        currentTitle = this.name[a] || getCaptionFileName(this.dataUrl[key])
      }
      if(Object.prototype.toString.call(this.name) === '[object String]'){
        currentTitle = this.name || getCaptionFileName(this.dataUrl[key])
      }
      if(!currentTitle){
        currentTitle = getCaptionFileName(this.dataUrl[key])
      }
      console.log('title = ====>',currentTitle,key,this.name,this.dataUrl);
      this.winConfig.title = currentTitle
    },
    setWatermarkFile(data) {
      const res = base64Img2Blob(data, window)
      console.log('setWatermarkFile====>', res)
      this.downLoadWatermarkFile = res
    },
    // 放大
    enlarge() {
      // madalClass
      if (this.isEnlarge) {
        // 还原
        this.madalClass = ''
        this.enlargeLabel = '全 屏'
        this.winConfig.width = '50vw'
        this.winConfig.height = '50vh'
      } else {
        // 放大
        this.enlargeLabel = '还 原'
        this.madalClass = 'ps-con-modal'
        this.winConfig.width = '100vw'
        this.winConfig.height = '100vh'
      }
      this.isEnlarge = !this.isEnlarge
    },
    modalEvent(type) {
      // 关闭
      this.winConfig.visible = false
      this.winConfig.width = '50vw'
      this.winConfig.height = '60vh'
      this.componentConfig.componentName = ''
      this.dataUrl = ''
      this.isEnlarge = false
      this.madalClass = ''
      this.enlargeLabel = '全 屏'
      this.event && this.event('close')
    },
    dataHandling(val, key,index) {
      this.downLoadWatermarkFile = null
      const suffix_ = getFileSuffix(val)
      this.fileName[key] = this.name || suffix_.name
      // console.log('suffix_===>',suffix_,this.suffix);
      let currentSuffix = ''
      let currentTitle = ''
      if(Object.prototype.toString.call(this.suffix) === '[object Array]'){
        currentSuffix = this.suffix[index] || suffix_.suffix
      }
      if(Object.prototype.toString.call(this.suffix) === '[object String]'){
        currentSuffix = this.suffix || suffix_.suffix
      }
      // console.log('后缀========》',currentSuffix,this.suffix,index,suffix_.suffix);
      if(Object.prototype.toString.call(this.name) === '[object Array]'){
        currentTitle = this.name[index] || getCaptionFileName(val)
      }
      if(Object.prototype.toString.call(this.name) === '[object String]'){
        currentTitle = this.name || getCaptionFileName(val)
      }

      // this.name || getCaptionFileName(url)

      this.getComponentInfo(currentSuffix, val, key,currentTitle)
    },
    getComponentInfo(fileType, url, index,title_) {
      console.log('getComponentInfo====>',fileType, url, index);
      const documentFun = () => {
        this.componentNameList[index] = 'iframeBox'
        // `https://view.officeapps.live.com/op/view.aspx?src=${url}`
        this.dataUrl[index] = `https://view.officeapps.live.com/op/view.aspx?src=${url}`
      }

      const imgFun = () => {
        // console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2222',this.componentNameList,this.dataUrl);
        this.componentNameList[index] = 'imgBox'
        this.dataUrl[index] = url
      }
      const textFun = () => {
        this.componentNameList[index] = 'textBox'
        this.dataUrl[index] = url
        fetch(this.dataUrl[index]).then((res) => {
          res.blob().then((blob) => {
            var reader = new FileReader() //这是核心,读取操作就是由它完成.
            reader.readAsText(blob, 'utf8') //读取文件的内容,也可以读取文件的URL
            reader.onload = function () {
              // console.log('this.result===>', this.result);
              //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
              document.getElementById('txtBox').innerHTML = this.result
            }
          })
        })
      }

      const getInfo = {
        xlsx: documentFun,
        xls: documentFun,
        pptx: documentFun,
        ppt: documentFun,
        doc: documentFun,
        docx: documentFun,
        jpg: imgFun,
        png: imgFun,
        jpeg: imgFun,
        pdf: () => {
          this.componentNameList[index] = 'pdfBox'
          // // this.dataUrl = 'https://zxcloud.oss-cn-hangzhou.aliyuncs.com/user/task/deliverables/1679882880287_%E6%9D%9C%E5%90%AF%E5%AE%97-%E6%84%8F%E5%A4%96%E9%99%A9%E7%94%B5%E5%AD%90%E4%BF%9D%E5%8D%9520221126-20231125-53.04.pdf' // url
          // this.dataUrl = 'https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/qsb/businessLicense/1679968661043_%E5%B0%8F%E7%BA%A2%E4%B9%A6(%E7%AC%AC%E5%9B%9B%E7%89%88).pdf' // url
          // this.AddWatermark.addWatermark(this.dataUrl).then(res=>{
          //     PDFObject.embed(res.url, "#pdfBox");
          //   })
          this.dataUrl[index] = url
          // this.$nextTick(() => {
          //   PDFObject.embed(this.dataUrl[index], '#pdfBox')
          // })
          // console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@3333',index,this.componentNameList,this.dataUrl);
        },
        txt: textFun,
        ofd: () => {
          this.dataUrl[index] = url
          this.componentNameList[index] = 'odfBox'
        },
      }
      if (this.config && !this.config.title && this.config.title != '--') {
        this.winConfig.title = title_ //  this.name || getCaptionFileName(url)
      }
      const fileType_ = fileType
      getInfo[fileType_] && getInfo[fileType_]()
      if (!getInfo[fileType_]) {
        // 下载 downLondBox
        this.componentNameList[index] = 'downLondBox'
        this.dataUrl[index] = '#'
      }
    },
    //下载
    uploads() {
      let url = this.downLoadWatermarkFile || this.url
      //从链接上截取文件名
      let fileName = this.name || getCaptionFileName(url)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.setAttribute('target', '_blank')
      fileName && a.setAttribute('download', fileName)
      a.href = url
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
  },
}
</script>

<style lang="less">
.img-box {
  width: auto;
  height: 100%;
}

.data-con {
  height: 60vh;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  .carousel-con {
    .slick-slider {
      width: 100%;
      height: 100%;
      .slick-list {
        width: 100%;
        height: 100%;
      }
    }
  }
  .dots-item {
    li button {
      background: #000000;
    }
    li {
      &.slick-active button {
        background: #3205f7;
      }
    }
    .item-con {
      height: 100%;
    }
  }
  .custom-slick-arrow {
    width: 25px;
    height: 25px;
    font-size: 25px;
    // color: #f0f1f5;
    // background-color: rgb(10, 10, 10);
    opacity: 1;
    z-index: 100;
  }
  // .custom-slick-arrow:before {
  //   display: none;
  // }
  // .custom-slick-arrow:hover {
  //   opacity: 1;
  // }
  .slick-track {
    height: 100%;
    .slick-slide div {
      height: 100%;
      display: flex !important;
      justify-content: center;
      align-items: center;
    }
  }
}

.title-con {
  width: calc(100% - 50px);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;

  .title {
    flex: 1;
    display: flex;
    overflow: hidden;
    /*文本不会换行*/
    white-space: nowrap;
    /*当文本溢出包含元素时，以省略号表示超出的文本*/
    text-overflow: ellipsis;
    padding: 5px 0;
  }

  .btn-group {
    width: 200px;
  }
}

.ps-con-modal {
  top: 0px !important;
}
</style>
